package com.adv.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.adv.controller.base.BaseController;
import com.adv.model.Advertpos;
import com.adv.service.AdvertposService;
import com.adv.vo.ProductForm;

@Controller
public class ProductController extends BaseController {

	@Autowired
	AdvertposService advertposService;

	@RequestMapping("/product/list")
	public String list(ModelMap model) {
		return "product/list";
	}

	@ResponseBody
	@RequestMapping("/product/json")
	public Object getProductList() {
		return advertposService.getProductList();
	}

	@ResponseBody
	@RequestMapping("/product/state")
	public Object state(ModelMap model, Advertpos product) {
		logger.debug("change product state: " + product.toString());
		advertposService.changeStates(product);
		return "success";
	}

	@RequestMapping("/product/detail")
	public String detail(ModelMap model, Advertpos product) {
		logger.debug("change product state: " + product.toString());
		System.out.println("detail:" + product.toString());
		Advertpos entity = new Advertpos();
		entity = advertposService.getProductDetail(product);
		model.put("product", entity);
		return "product/detail";
	}

	@RequestMapping("/product/add")
	public String add(ProductForm form, ModelMap model) {
		List<Advertpos> advertisers = advertposService.getAdvertiser();
		if (null != form && null != form.getId()) {
			model.put("product", advertposService.getProductByPrimaryId(form.getId()));
		}
		model.put("advertisers", advertisers);
		return "product/modify";
	}

	@ResponseBody
	@RequestMapping("/product/save")
	public Object save(@Validated ProductForm product, @Valid BindingResult result, ModelMap model) {
		if (result.hasErrors()) {
			// 新建需要校验完整字段
			return convertField2Map(result);
		}
		return advertposService.saveProduct(product);
	}

	@RequestMapping("/product/page")
	public String upload(ModelMap model, String page, String icon, String bigimg) {
		model.put("icon", icon);
		model.put("bigimg", bigimg);
		return "product/" + page;
	}

	@ResponseBody
	@RequestMapping("/product/delete")
	public Object delete(ProductForm form) {
		if (null != form.getId()) {
			return advertposService.deleteProduct(form);
		}
		return failureMsg();
	}
}
